package com.xieyx.licenseplate;


import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;


/**
 * 电动车车牌
 */
public class ElectricLicensePlateTextView extends LinearLayout{

    private static final int[] VIEW_IDS = new int[]{
            R.id.item_code_iv1, R.id.item_code_iv2, R.id.item_code_iv3,
            R.id.item_code_iv4, R.id.item_code_iv5, R.id.item_code_iv6,
            R.id.item_code_iv7 };

    private TextView[] TextViews;

    private OnFrameTouchListener mTouchListener = new OnFrameTouchListener();

    private boolean isUpdateView = false;//是否更新view内容

    private int updateViewPosition;

    private static int ITEM_VIEW_COUNT = 7;

    private Context mContext;

    private LicensePlateDialog dialog;

    private String city = "";

    private LinearLayout llPlate;//车牌输入框

    private TextView tvNoPlate;//无牌

    private boolean isNoPlate = false;//是否无牌

    private LicensePlateDialogListener licensePlateDialogListener;

    public void setLicensePlateDialogListener(LicensePlateDialogListener listener){
        licensePlateDialogListener = listener;
    }


    public ElectricLicensePlateTextView(Context context) {
        super(context);
        mContext = context;
        init(context);
    }

    public ElectricLicensePlateTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init(context);
    }

    private void init(Context context){
        View view = LayoutInflater.from(context).inflate(R.layout.layout_electric_license_plate_frame,null);
        llPlate = view.findViewById(R.id.ll_plate);
        tvNoPlate = view.findViewById(R.id.tv_noPlate);
        int textsLength = VIEW_IDS.length;
        TextViews = new TextView[7];
        for (int i = 0; i < textsLength; i++) {
            //textview放进数组中，方便修改操作
            TextViews[i] = view.findViewById(VIEW_IDS[i]);
            TextViews[i].setOnTouchListener(mTouchListener);
        }
        if(dialog == null){
            dialog = new LicensePlateDialog(mContext);
        }
        addView(view);

        dialog.setOnKeyClickListener(new LicensePlateDialog.OnKeyClickListener() {
            @Override
            public void onKeyClick(String key) {
                if (key.equalsIgnoreCase("删")) {
                    isUpdateView = false;
                    updateViewPosition = 0;
                    tvNoPlate.setText("");

                    for(int i = TextViews.length-1;i >= 0 ; i--){
                        if(!TextUtils.isEmpty(TextViews[i].getText().toString())){
                            TextViews[i].setText("");
                            setTextViewsBackground(i);
                            switchKeyBoard(i);
                            break;
                        }
                    }

                } else if(key.equalsIgnoreCase("无牌")){
                    llPlate.setVisibility(GONE);
                    tvNoPlate.setVisibility(VISIBLE);
                    tvNoPlate.setText(key);
                    isNoPlate = true;
                }else{
                    isNoPlate = false;
                    tvNoPlate.setText("");
                    llPlate.setVisibility(VISIBLE);
                    tvNoPlate.setVisibility(GONE);
                    setEditText(key);
                }
            }
        });
        tvNoPlate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!dialog.isShowing()){
                    if(licensePlateDialogListener != null){
                        licensePlateDialogListener.onLicensePlateDialogShow();
                    }
                    dialog.showDiaLog();
                    dialog.switchElectricCityList();
                }
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if(licensePlateDialogListener != null){
                    licensePlateDialogListener.onLicensePlateDialogHide();
                }
            }
        });
    }

    /**
     * 设置输入内容
     */
    private void setEditText(String key){
        if (isUpdateView) {

            TextViews[updateViewPosition].setText(key);
            setTextViewsBackground(updateViewPosition);

            if(updateViewPosition+1 < ITEM_VIEW_COUNT){

                if(!TextUtils.isEmpty(TextViews[updateViewPosition].getText().toString())){
                    updateViewPosition ++;
                }else{
                    isUpdateView = false;
                }
            }else{
                isUpdateView = false;
            }
            switchKeyBoard(updateViewPosition);
        } else {
            for (int i = 0; i < TextViews.length; i++) {
                if(TextUtils.isEmpty(TextViews[i].getText().toString())){
                    TextViews[i].setText(key);
                    setTextViewsBackground(i);
                    switchKeyBoard(i+1);
                    break;
                }
            }
        }
    }

    /**
     * 获取车牌
     */
    public String getPlateText(){
        String plate = "";

        if(isNoPlate){
            plate = tvNoPlate.getText().toString();
            return plate;
        }
        for(int i = 0;i < TextViews.length;i++){
            if(TextUtils.isEmpty(TextViews[i].getText().toString())){
                plate = "";
                break;
            }
            plate = plate+TextViews[i].getText().toString();
        }

        return plate;
    }

    /**
     * 设置车牌
     */
    public void setPlateText(String plate){
        if(TextUtils.isEmpty(plate) || plate.contains("无")){
            isNoPlate = true;
            llPlate.setVisibility(GONE);
            tvNoPlate.setVisibility(VISIBLE);
            tvNoPlate.setText("无牌");
            return;
        }

        if(plate.length() < 4){
            return;
        }
        try {
            TextViews[0].setText(plate.substring(0,2));
            TextViews[1].setText(plate.substring(2,4));

            plate = plate.substring(4);

            for(int i = 0;i<plate.length();i++){
                TextViews[i+2].setText(plate.substring(i,i+1));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 清空内容
     */
    public void cleatText(){
        tvNoPlate.setEnabled(false);
        for(int i = 0;i<TextViews.length;i++){
            TextViews[i].setText("");
        }
    }

    /**
     * 设置不可编辑
     */
    public void setPlateEnable(){
        for(int i = 0;i<TextViews.length;i++){
            TextViews[i].setEnabled(false);
        }
    }

    /**
     * 设置背景
     * @param position
     */
    private void setTextViewsBackground(int position) {
        for (int i = 0; i < ITEM_VIEW_COUNT; i++) {
            TextViews[i].setBackgroundResource(R.drawable.license_plate_mid_view_bg);
        }
        TextViews[position].setBackgroundResource(R.drawable.license_plate_mid_view_blue);
    }

    /**
     * 根据内容切换键盘
     */
    private void switchKeyBoard(int index){
        city = TextViews[0].getText().toString();
        if (index == 0) {
            dialog.switchElectricCityList();
        } else if (index == 1) {
            dialog.switchElectricAreaList(city);
        }else {
            dialog.switchNum();
        }
    }


    /**
     * 显示输入框的TouchListener
     */
    private class OnFrameTouchListener implements OnTouchListener {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            if (view instanceof TextView) {
                if(!dialog.isShowing()){
                    if(licensePlateDialogListener != null){
                        licensePlateDialogListener.onLicensePlateDialogShow();
                    }
                    dialog.showDiaLog();
                }

                TextView tv = (TextView) view;
                tv.setFocusable(true);
                String tvString = (String) tv.getText();
                int viewId = tv.getId();

                //点击时有值，执行修改
                if (!TextUtils.isEmpty(tvString)) {
                    for (int i = 0; i < TextViews.length; i++) {
                        if (viewId == VIEW_IDS[i]) {
                            updateViewPosition = i;
                            switchKeyBoard(i);
                            isUpdateView = true;
                            setTextViewsBackground(i);
                        }
                    }
                }else{//点击光标在末尾
                    isUpdateView = false;
                    if(TextUtils.isEmpty(TextViews[0].getText().toString())){
                        switchKeyBoard(0);
                    }else {
                        for (int i = TextViews.length-1; i >= 0; i--) {
                            if (!TextUtils.isEmpty(TextViews[i].getText().toString())) {
                                switchKeyBoard(i+1);
                                break;
                            }
                        }
                    }
                }
            }
            return true;
        }
    }
}
